package com.itliang.service.system.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itliang.core.model.dto.system.sysmenu.AssignMenuRequest;
import com.itliang.core.model.entity.system.SysMenu;
import com.itliang.core.model.entity.system.SysRoleMenu;
import com.itliang.core.model.vo.RouterVo;
import com.itliang.core.result.CodeEnum;
import com.itliang.exception.BusinessException;
import com.itliang.mapper.system.SysMenuMapper;
import com.itliang.mapper.system.SysRoleMenuMapper;
import com.itliang.service.system.SysMenuService;
import com.itliang.utils.MenuHelper;
import com.itliang.utils.RouterUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @author liangzhuoyuan
 * @description 针对表【sys_menu(菜单表)】的数据库操作Service实现
 */
@Service
public class SysMenuServiceImpl extends ServiceImpl<SysMenuMapper, SysMenu>
        implements SysMenuService {

    @Resource
    SysMenuMapper sysMenuMapper;

    @Resource
    SysRoleMenuMapper sysRoleMenuMapper;

    /**
     * 菜单列表（树形）
     *
     * @return
     */
    @Override
    public List<SysMenu> listMenuNodes() {
        // 1、获取所有菜单
        QueryWrapper<SysMenu> wrapper = new QueryWrapper<>();
        wrapper.orderByAsc("sort_value");
        List<SysMenu> sysMenuList = sysMenuMapper.selectList(wrapper);
        // 2、所有菜单数据转换为要求的数据格式
        return MenuHelper.buildTree(sysMenuList);
    }

    /**
     * 根据 id 删除菜单
     *
     * @param id
     * @return
     */
    @Override
    public boolean deleteMenuById(Long id) {
        long count = this.count(new QueryWrapper<SysMenu>().eq("parent_id", id));
        if (count > 0) {
            throw new BusinessException(CodeEnum.DELETE_MENU_ERROR);
        }
        boolean b = this.removeById(id);
        return b;
    }

    /**
     * 根据角色获取菜单
     *
     * @param id
     * @return
     */
    @Override
    public List<SysMenu> getSysMenuByRoleId(Long id) {
        // 1、获取所有菜单 status=1 可用
        List<SysMenu> sysMenuList = baseMapper.selectList(new LambdaQueryWrapper<SysMenu>().eq(SysMenu::getStatus, 1));
        // 2、根据角色id查询，角色分配过的菜单列表
        List<SysRoleMenu> roleMenus = sysRoleMenuMapper.selectList(new LambdaQueryWrapper<SysRoleMenu>().eq(SysRoleMenu::getRoleId, id));
        // 3、从第二步查询列表中，获取角色分配所有菜单id
        List<Long> roleMenuIds = new ArrayList<>();
        for (SysRoleMenu roleMenu : roleMenus) {
            roleMenuIds.add(roleMenu.getMenuId());
        }
        // 4、数据处理：idSelect true选中 否则false
        for (SysMenu sysMenu : sysMenuList) {
            if (roleMenuIds.contains(sysMenu.getId())) {
                sysMenu.setIsSelect(true);
            } else {
                sysMenu.setIsSelect(false);
            }
        }
        // 转换成菜单树形结构
        List<SysMenu> result = MenuHelper.buildTree(sysMenuList);

        return result;
    }

    /**
     * 给角色分配权限
     *
     * @param assignMenuRequest
     */
    @Override
    public void doAssign(AssignMenuRequest assignMenuRequest) {
        //删除已分配的权限
        sysRoleMenuMapper.delete(new QueryWrapper<SysRoleMenu>().eq("role_id", assignMenuRequest.getRoleId()));
        //遍历所有已选择的权限id
        for (Long menuId : assignMenuRequest.getMenuIdList()) {
            if (menuId != null) {
                //创建SysRoleMenu对象
                SysRoleMenu sysRoleMenu = new SysRoleMenu();
                sysRoleMenu.setMenuId(menuId);
                sysRoleMenu.setRoleId(assignMenuRequest.getRoleId());
                //添加新权限
                sysRoleMenuMapper.insert(sysRoleMenu);
            }
        }
    }

    /**
     * 根据userId查询菜单权限值
     *
     * @param userId 用户id
     * @return
     */
    @Override
    public List<RouterVo> getUserMenuList(Long userId) {
        //超级管理员admin账号id为：1
        List<SysMenu> sysMenuList = null;
        if (userId == 1) {
            sysMenuList = sysMenuMapper.selectList(new QueryWrapper<SysMenu>().eq("status", 1).orderByAsc("sort_value"));
        } else {
            sysMenuList = sysMenuMapper.getMenuListByUserId(userId);
        }
        //构建树形数据
        List<SysMenu> sysMenuTreeList = MenuHelper.buildTree(sysMenuList);

        //构建路由
        List<RouterVo> routerVoList = RouterUtils.buildRouters(sysMenuTreeList);

        return routerVoList;
    }

    /**
     * 根据userId查询按钮权限值
     *
     * @param userId
     * @return
     */
    @Override
    public List<String> getUserButtonList(Long userId) {
        List<SysMenu> sysMenuList = null;
        if (userId == 1) {
            sysMenuList = sysMenuMapper.selectList(new QueryWrapper<SysMenu>().eq("status", 1).orderByAsc("sort_value"));
        } else {
            sysMenuList = sysMenuMapper.getMenuListByUserId(userId);
        }

        ArrayList<String> permissionList = new ArrayList<>();
        for (SysMenu sysMenu : sysMenuList) {
            if (sysMenu.getType() == 2) {
                String perms = sysMenu.getPerms();
                permissionList.add(perms);
            }
        }

        return permissionList;
    }
}




